#include <iostream>

#include "Log.hpp"
#include "Reactor.hpp"
#include "Listener.hpp"
#include "Channel.hpp"
#include "Log.hpp"
#include "Common.hpp"
#include "Protocal.hpp"
#include "NetCal.hpp"

using namespace LogModule;

int main(int argc, char *argv[])
{
    // 输入格式错误
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        exit(USAGE_ERR);
    }

    logger.EnableConsoleLogStrategy(); // 开启控制台日志策略

    int port = std::stoi(argv[1]); // 获取输入端口号

    std::shared_ptr<Cal> cal = std::make_shared<Cal>(); // 创建Cal业务对象
    // 创建协议对象
    std::shared_ptr<Protocol> protocol = std::make_shared<Protocol>([&cal](Request &req)
                                                                    { return cal->Execute(req); });

    std::shared_ptr<Connection> conn = std::make_shared<Listener>(port); // 创建listener对象
    conn->RegsiterHandler([&protocol](std::string &inbuffer) -> std::string{
        LOG(LogLevel::DEBUG) << "enter Listener lamda RegsiterHandler begin";

        std::string response_str;
        while (1)
        {
            std::string package;
            // protocol对Channel进行解码处理
            if(!protocol->Decode(inbuffer, &package))
                //return std::string(); // 报文不完整, 直接返回
                break;
            // 报文完整
            response_str += protocol->Execute(package); // 业务处理, 得到响应报文
        }
        
        LOG(LogLevel::DEBUG) << "enter Listener lamda RegsiterHandler end, response_str: " << response_str;
        return response_str; 
    });

    std::unique_ptr<Reactor> R = std::make_unique<Reactor>(); // 创建Reactor对象

    R->AddConnection(conn); // 将Listner型Connection对象添加到TcpServer中

    R->Loop(); // 启动TcpServer

    return 0;
}